<template>
  <base-load-page :loadState="false" class="base-load-page">
    <template #head>
      <div style="padding-bottom: 15px" class="head-box">
        <div class="left-box">
          <base-input-search
            v-model="filterData.dramaTitle"
            clearable
            placeholder="请输入短剧名称"
            style="width: 100%"
            :prefixIcon="IconSearch"
            @submit="getAxiosData(true)"
          ></base-input-search>
          <base-input-search
            v-model="filterData.thirdAdvertiserId"
            clearable
            placeholder="请输入广告主id"
            style="width: 100%"
            :prefixIcon="IconSearch"
            @submit="getAxiosData(true)"
          ></base-input-search>
          <base-input-search
            v-model="filterData.referralLinkId"
            clearable
            placeholder="请输入推广链接id"
            style="width: 100%"
            :prefixIcon="IconSearch"
            @submit="getAxiosData(true)"
          ></base-input-search>
          <base-input-search
            v-model="filterData.createName"
            clearable
            placeholder="请输入投放人"
            style="width: 100%"
            :prefixIcon="IconSearch"
            @submit="getAxiosData(true)"
          ></base-input-search>
          <bubble-select-local
            v-model="filterData.referralLinkType"
            labelKey="label"
            valueKey="value"
            :filterable="false"
            style="width: 100%"
            :list="referralLinkTypeOptions"
            placeholder="请选择推广链接类型"
            @change="getAxiosData(true)"
          ></bubble-select-local>
          <bubble-select-local
            v-model="filterData.pullStatus"
            labelKey="label"
            valueKey="value"
            :filterable="false"
            style="width: 100%"
            :list="[
              { label: '启用', value: 1 },
              { label: '停用', value: 0 },
            ]"
            placeholder="请选择启用状态"
            @change="getAxiosData(true)"
          ></bubble-select-local>
          <bubble-select-local
            v-model="filterData.deptId"
            labelKey="deptName"
            valueKey="deptId"
            :filterable="false"
            style="width: 100%"
            :list="deptListOptions as Record<string, any>[]"
            placeholder="请选择部门"
            @change="getAxiosData(true)"
          ></bubble-select-local>
        </div>
        <div class="right-box">
          <el-button type="success" :icon="IconPlus" @click="handleAddPromotionLink()">添加绑定</el-button>
        </div>
      </div>
    </template>
    <el-table ref="elTableRef" v-loading="baseData.loading" border height="100%" :data="tableData" showOverflowTooltip stripe style="width: 100%">
      <template #empty>
        <base-empty style="width: 100%" :description="description" :pageLoadButton="[{ text: '重新加载', callBack: () => getAxiosData() }]"></base-empty>
      </template>
      <el-table-column
        fixed
        type="index"
        :index="(index: number) => (filterData.current - 1) * filterData.size + index + 1"
        label="编号"
        sortable
        width="60"
        align="center"
        headerAlign="center"
      ></el-table-column>
      <el-table-column label="第三方广告主账户" minWidth="220">
        <template #default="{ row }">
          <div class="content-wrap">
            <p>
              账户ID:
              <span class="highlighted" @click="clipboard(row.thirdAdvertiserId)">{{ row.thirdAdvertiserId }}</span>
            </p>
            <p>
              账户名:
              <span>{{ row.thirdAdvertiserName || '-' }}</span>
            </p>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="推广链接" prop="referralLinkId" minWidth="220">
        <template #default="{ row }">
          <div class="content-wrap">
            <p>
              推广链接ID:
              <span class="highlighted" @click="clipboard(row.referralLinkId)">{{ row.referralLinkId }}</span>
            </p>
            <p>
              推广名称:
              <span>{{ row.referralLinkName || '-' }}</span>
            </p>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="短剧名称" prop="dramaTitle" minWidth="200">
        <template #default="{ row }">
          <div style="cursor: pointer" @click="clipboard(row.dramaTitle)">
            {{ row.dramaTitle }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="投放人" prop="createName" minWidth="80"></el-table-column>
      <el-table-column label="拉取数据开始时间" prop="createTime" minWidth="160"></el-table-column>
      <el-table-column label="拉取数据结束时间" prop="endTime" minWidth="160"></el-table-column>
      <el-table-column label="应用类型" prop="appType" minWidth="90">
        <template #default="{ row }">
          <el-tag v-if="row.appType === 1" key="el-tag-1" type="warning" size="small">抖小</el-tag>
          <el-tag v-else-if="row.appType === 3" key="el-tag-2" size="small">微小</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="推广链接类型" prop="referralLinkType" minWidth="110">
        <template #default="{ row }">
          {{ referralLinkTypeOptions.find((v) => v.value === row.referralLinkType)?.label || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="拉取启用状态" prop="pullStatus" minWidth="110">
        <template #default="{ row }">
          <el-switch
            v-model="row.pullStatus"
            style="--el-switch-on-color: var(--el-color-success); --el-switch-off-color: var(--el-color-danger)"
            inlinePrompt
            activeText="启用"
            inactiveText="停用"
            :activeValue="1"
            :inactiveValue="0"
            :loading="row._statusLoading"
            :beforeChange="() => handleSetStateSingle(row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column sortable fixed="right" label="操作" width="100" align="center" headerAlign="center">
        <template #default="{ row }">
          <div style="display: flex; flex-direction: column; gap: 4px; overflow: hidden">
            <el-button link type="primary" size="small" style="margin-left: 0" :icon="IconEdit" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="primary" size="small" style="margin-left: 0" :icon="EpDataLine" @click="handleDayConsume(row)">每日消耗</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <template #foot>
      <div class="pagination-box">
        <el-pagination
          v-model:currentPage="filterData.current"
          v-model:pageSize="filterData.size"
          :pageSizes="[20, 30, 40, 50]"
          :disabled="baseData.loading"
          :pagerCount="13"
          layout="total, prev, pager, next, sizes, jumper"
          :total="baseData.total"
          @change="getAxiosData(true)"
        ></el-pagination>
      </div>
    </template>
    <add-bind-data ref="addBindDataRef"></add-bind-data>
  </base-load-page>
</template>

<script setup lang="ts">
  import IconSearch from '~icons/ep/search';
  import IconPlus from '~icons/ep/plus';
  import IconEdit from '~icons/ep/edit';
  import EpDataLine from '~icons/ep/data-line';

  import { useClipboard } from '@vueuse/core';
  import {
    type OceAdvertiserReferralRelationItem,
    type OceAdvertiserReferralRelationReq,
    getOceAdvertiserReferralRelation,
    updateStateOceAdvertiserReferralRelation,
  } from '@/api/marketing-management';
  import addBindData from './components/add-bind-data.vue';
  import { referralLinkTypeOptions } from '@/views/app-main/marketing-management/selectorOptions.ts';
  import { type DeptItem, getSysDeptListAxios } from '@/api/permission-management.ts';

  const { copy, isSupported } = useClipboard({ legacy: true });
  const router = useRouter();
  const addBindDataRef = ref<InstanceType<typeof addBindData>>();
  const elTableRef: $RefComp<'ElTable'> = ref(null);
  const baseData = shallowReactive({
    /** 加载状态 */
    loading: true,
    /** 总数量 */
    total: 0,
  });

  const filterData = ref<OceAdvertiserReferralRelationReq>({
    current: 1,
    size: 40,
    dramaTitle: '',
    referralLinkId: '',
    thirdAdvertiserId: '',
    createName: '',
    referralLinkType: '',
    pullStatus: '',
    deptId: '',
  });

  type TableItem = OceAdvertiserReferralRelationItem & {
    _statusLoading?: boolean;
  };

  const tableData: Ref<TableItem[]> = ref([]);
  const deptListOptions: Ref<DeptItem[]> = ref([]);
  const description = ref('');
  onMounted(() => {
    getAxiosData();
    handleGetSysDeptListAxios();
  });

  /**
   * 设置表格数据
   */
  async function getAxiosData(showLoading = true) {
    try {
      await nextTick();
      baseData.loading = Boolean(showLoading);
      const res = await getOceAdvertiserReferralRelation(filterData.value);
      tableData.value = res.data.records;
      description.value = '暂无数据';
      filterData.value.current = res.data.current;
      filterData.value.size = res.data.size;
      baseData.total = res.data.total;
      baseData.loading = false;
    } catch (error) {
      baseData.loading = false;
      tableData.value = [];
      description.value = error.msg || '加载失败，-BD001';
    }
  }

  /** 新增推广链接 */
  function handleAddPromotionLink() {
    addBindDataRef.value?.show({
      action: 'add',
      addCallBack() {
        getAxiosData();
      },
    });
  }

  /** 编辑推广链接 */
  function handleEdit(row: TableItem) {
    addBindDataRef.value?.show({
      action: 'edit',
      recordData: row,
      editCallBack() {
        getAxiosData();
      },
    });
  }

  /** 跳转每日消耗 */
  function handleDayConsume(row?: any) {
    if (row.referralLinkType > 3) {
      router.push(`/marketing-management/iaa-juliang-daily-consumption?referralLinkId=${row.referralLinkId}`);
    } else {
      router.push(`/marketing-management/juliang-daily-consumption?referralLinkId=${row.referralLinkId}`);
    }
  }

  /** 停用提示 */
  function disabledTip(row: TableItem) {
    console.log(row.pullStatus);

    if (row.pullStatus === 0) {
      return Promise.resolve(true);
    }
    return new Promise((res) => {
      ElMessageBox.confirm('关闭后，不再拉取巨量消耗数据.', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
      })
        .then(() => {
          res(true);
        })
        .catch(() => {
          res(false);
        });
    });
  }

  /** 修改状态 */
  async function handleSetStateSingle(row: TableItem): Promise<boolean> {
    const name = row.pullStatus === 0 ? '启用' : '停用';

    const val = await disabledTip(row);

    if (val) {
      try {
        row._statusLoading = true;
        await updateStateOceAdvertiserReferralRelation({ advertiserReferralId: row.advertiserReferralId! });
        row._statusLoading = false;
        ElToast.success(`${name}成功`);
        return Promise.resolve(true);
      } catch (error) {
        row._statusLoading = false;

        ElToast.error(error.msg || `${name}失败，-BD004`);
        return Promise.reject(false);
      }
    } else {
      return Promise.resolve(false);
    }
  }

  /** 部门列表 */
  function handleGetSysDeptListAxios() {
    getSysDeptListAxios({}).then((res) => {
      deptListOptions.value = res.data;
    });
  }

  /** 复制 */
  async function clipboard(text: string) {
    if (!isSupported) {
      ElToast.error('您的浏览器不支持复制');
    } else {
      try {
        await copy(text);
        ElToast.success('复制成功');
      } catch (error) {
        ElToast.error('复制失败');
      }
    }
  }
</script>

<style lang="scss" scoped>
  .pagination-box {
    @include flex(row, nowrap, center, center, center);
    padding-top: 15px;
  }

  .head-box {
    @include flex(row, nowrap, flex-start, center, center);
    align-items: start;

    .left-box {
      display: grid;
      flex: 1;
      grid-template-columns: repeat(auto-fill, minmax(210px, 1fr));
      grid-gap: 15px;
      margin-right: 15px;
    }
  }

  .content-wrap {
    // padding: 8px 0;
    white-space: wrap;
  }
</style>
